package com.yvan.leto.server.controller;

import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.yvan.leto.server.domain.ReleaseLog;
import com.yvan.leto.server.service.ReleaseService;
import com.yvan.leto.server.utils.HttpUtil;
import com.yvan.platform.ResultModel;
import com.yvan.platform.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@RestController
@Slf4j
public class ReleaseController {

    @Autowired
    private ReleaseService releaseService;

    @GetMapping("/releases.htm")
    public ModelAndView index() {
        return new ModelAndView("/releases.ftl");
    }

    @PostMapping("/releases.json")
    public Object getRelease(@RequestParam(value = "rows", required = false, defaultValue = "10") int rows,
                             @RequestParam(value = "page", required = false, defaultValue = "1") int page) {

        Pagination pagination = new Pagination(page, rows);
        List<ReleaseLog> row = releaseService.logs(pagination);
        return HttpUtil.writeJqgridResult(row, pagination);
    }

    @PostMapping("/release/project.json")
    public Object releaseProject(@RequestParam(required = false, value = "env", defaultValue = "") String env,
                                 @RequestParam("project") String project,
                                 @RequestParam("msg") String msg) {
        if (StringUtils.isBlank(env)) {
            env = HttpUtil.getCookieValue("env");
        }
        releaseService.publishProject(env, project, msg);
        return ResultModel.newSuccess();
    }

    @PostMapping("/release/env.json")
    public Object releaseProject(@RequestParam(required = false, value = "env", defaultValue = "") String env,
                                 @RequestParam("msg") String msg) {
        if (StringUtils.isBlank(env)) {
            env = HttpUtil.getCookieValue("env");
        }
        releaseService.publishEnv(env, msg);
        return ResultModel.newSuccess();
    }
}
